package com.hliushi.demo.web;

import com.hliushi.demo.anno.CurrentUser;
import com.hliushi.demo.entity.User;
import com.hliushi.demo.entity.UserEntity;
import com.hliushi.demo.service.LoginService;
import com.hliushi.demo.web.vo.UserLoginVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * @author llhuang10
 * @date 2021/8/24 16:25
 */
@Slf4j
@RestController
@RequestMapping("/user")
public class UserResource {

    @Resource
    private LoginService loginService;


    public UserResource() {
    }

    public UserResource(LoginService loginService) {
        this.loginService = loginService;
    }

    @PostMapping("/save")
    public String save(User user) {
        log.info("UserController save ....{}", user);
        return user.getName();
    }

    /**
     * 获取当前系统登录用户
     *
     * @param user 通过参数解析器帮我们把User对象注入到容器
     * @return user
     */
    @GetMapping("/get-current-user")
    public String getCurrentUser(@CurrentUser User user) {
        String name = user.getName();
        log.info("======== UserController name = {}", name);
        return user.toString();
    }

    /**
     *
     */
    @PostMapping("/login")
    public void login(@RequestBody UserLoginVO vo) {
        loginService.login(vo.getAccount(), vo.getPassword());
    }

    @PostMapping("/login/request")
    public String loginByRequest(HttpServletRequest request) {
        String account = request.getParameter("account");
        String password = request.getParameter("password");

        try {
            UserEntity user = loginService.loginUnSupport(account, password);
            if (user == null) {
                return "/login";
            } else {
                return "/index.jsp";
            }
        } catch (Exception e) {
            return "/505";
        }
    }

}
